#coding: UTF-8

"""
实现类似dictmatch的机制
"""

from pygtrie import *
import sys

class DictMatch:
    def __init__(self):
        self.trie = Trie()
        self.vocab_num = 0

    def load_from_dict(self, dt):
        """
        默认输出查询的是utf-8， 这样迭代出来的字符串是正确的
        value 不强调
        """    
        if type(dt) != type({}):
            return 0

        for key in dt:
            self.trie[key] = dt[key]

        self.vocab_num = len(self.trie)

    def prefix_match(self, s):
        res = self.trie.prefixes(s)
        #print "prefix size", len(res)
        ns = []
        for itm in res:
            #print itm
            s = itm[0]
            val = itm[1]
            s = u''.join(s)
            ns.append([s, val]  )
        return ns

    def match_all(self, s):
        res = []
        #遍历每个词
        for i in range(len(s)):
            substr = s[i:]
            pres = self.prefix_match(substr)
            for ores in pres:
                sstr, val = ores
                ndict = {}
                ndict[u"str"] = sstr
                ndict[u"val"] = val
                ndict[u"beg"] = i
                ndict[u"len"] = len(sstr)
                res.append(ndict)
                
        return res
        
if __name__ == "__main__":
    line = u"为什么是蓝色的"
    dm = DictMatch()
    dt = {u"为什么":1, u"什么":2, u"为什":3, u"蓝色":4}
    dm.load_from_dict(dt)

    res = dm.prefix_match(line)
    print dm
    for k,v in res:
        print k.encode("UTF-8"), v
    
    line = u"天空为什么是蓝色的"
    print line.encode("UTF-8")    
    res = dm.match_all(line)
    for ores in res:
        l = [u"str:%s"%(ores["str"]) , u"val:%s"%(ores["val"]) , u"beg:%s"%(ores["beg"]), u"len:%s"%(ores["len"])]
        l = [i.encode("UTF-8") for i in l]
        print "\t".join(l)


        
        
